package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.dao.GoodsTypeDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.entity.GoodsType;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.service.CustomerReturnListGoodsService;
import com.atguigu.jxc.service.GoodsService;
import com.atguigu.jxc.service.LogService;
import com.atguigu.jxc.service.SaleListGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private GoodsTypeDao goodsTypeDao;

    @Override
    public ServiceVO<Object> getCode() {

        // 获取当前商品最大编码
        String code = goodsDao.getMaxCode();

        // 在现有编码上加1
        int intCode = Integer.parseInt(code) + 1;

        // 将编码重新格式化为4位数字符串形式
        StringBuilder unitCode = new StringBuilder(Integer.toString(intCode));

        for (int i = 4; i > Integer.toString(intCode).length(); i--) {

            unitCode.insert(0, "0");

        }
        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS, unitCode.toString());
    }

    /**
     * 首页查询库存商品
     *
     * @param page        页码
     * @param rows        行数
     * @param codeOrName  商品编码或名称
     * @param goodsTypeId 商品类型Id
     * @return Map
     */
    @Override
    public Map<String, Object> listInventory(Integer page, Integer rows, String codeOrName, Integer goodsTypeId) {
        return getResultMap(page, rows, codeOrName, goodsTypeId);
    }

    /**
     * 查询所有商品信息
     *
     * @param page        页码
     * @param rows        行数
     * @param goodsName   商品名称
     * @param goodsTypeId 商品类型Id
     * @return Map
     */
    @Override
    public Map<String, Object> getGoodsList(Integer page, Integer rows, String goodsName, Integer goodsTypeId) {
        return getResultMap(page, rows, goodsName, goodsTypeId);
    }

    @Override
    public ServiceVO<Object> saveOrUpdateGoods(Goods goods) {
        int count = 0;
        //判断id为空时，说明是新增操作
        if (goods.getGoodsId() == null) {
            //初始化库存数量为0
            goods.setInventoryQuantity(0);
            //初始化上次进价
            goods.setLastPurchasingPrice(0);
            //初始化状态为0
            goods.setState(0);
            count = goodsDao.saveGoods(goods);
        } else {
            if ((goods.getInventoryQuantity() == null) || (goods.getState() == null)) {
                //初始化库存数量为0
                goods.setInventoryQuantity(0);
                //初始化上次进价
                goods.setLastPurchasingPrice(0);
                //初始化状态为0
                goods.setState(0);
            }
            count = goodsDao.UpdateGoods(goods);
        }
        if (count > 0) {
            return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS, count);
        }
        return new ServiceVO<>(ErrorCode.UPDATE_OR_ADD_ERROR_CODE, ErrorCode.UPDATE_OR_ADD_ERROR_MESS, count);
    }

    /**
     * 删除商品
     *
     * @param goodsId 商品Id
     * @return ServiceVO
     */
    @Override
    public ServiceVO<Object> deleteGoods(Integer goodsId) {
        //判断商品的状态
        Goods goods = goodsDao.getGoodsById(goodsId);
        //判断商品的状、入库、有进货销售单据不能删除
        if (goods.getState() == 0) {
            int count = goodsDao.deleteGoodsByGoodsId(goodsId);
            if (count > 0) {
                return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS, count);
            }
        } else if (goods.getState() == 1) {
            return new ServiceVO<>(ErrorCode.STORED_ERROR_CODE, ErrorCode.STORED_ERROR_MESS, goods.getGoodsId());
        } else if (goods.getState() == 2) {
            return new ServiceVO<>(ErrorCode.HAS_FORM_ERROR_CODE, ErrorCode.HAS_FORM_ERROR_MESS, goods.getGoodsId());
        }
        return new ServiceVO<>(ErrorCode.DELETE_ERROR_CODE, ErrorCode.DELETE_ERROR_MESS, goods.getGoodsId());
    }

    /**
     * 查询无库存商品
     *
     * @param page        页码
     * @param rows        行数
     * @param nameOrCode  商品名称或code
     * @return Map
     */
    @Override
    public Map<String, Object> getNoInventoryQuantity(Integer page, Integer rows, String nameOrCode) {
        Map<String, Object> result = new HashMap<>();

        List<Goods> resultGoodsList = new ArrayList<>();
        page = (page - 1) * rows;
        //根据名称或code查询所有商品
        List<Goods> goods = goodsDao.listInventory(page, rows, nameOrCode, null);
        if (goods != null) {
            goods.forEach(good -> {
                if (good.getInventoryQuantity() <= 0){
                    resultGoodsList.add(good);
                }
            });
            int total = resultGoodsList.size();
            result.put("total", total);
            result.put("rows", resultGoodsList);
            return result;
        }
        return result;
    }

    /**
     * 查询有库存商品
     *
     * @param page        页码
     * @param rows        行数
     * @param nameOrCode  商品名称或code
     * @return Map
     */
    @Override
    public Map<String, Object> getHasInventoryQuantity(Integer page, Integer rows, String nameOrCode) {
        Map<String, Object> result = new HashMap<>();

        List<Goods> resultGoodsList = new ArrayList<>();
        page = (page - 1) * rows;
        //根据名称或code查询所有商品
        List<Goods> goods = goodsDao.listInventory(page, rows, nameOrCode, null);
        if (goods != null) {
            goods.forEach(good -> {
                if (good.getInventoryQuantity() > 0){
                    resultGoodsList.add(good);
                }
            });
            int total = resultGoodsList.size();
            result.put("total", total);
            result.put("rows", resultGoodsList);
            return result;
        }
        return result;
    }

    /**
     * 库存入库
     *
     * @param goodsId            商品Id
     * @param inventoryQuantity  库存数量
     * @param purchasingPrice    进价
     * @return ServiceVO
     */
    @Override
    public ServiceVO<Object> saveStock(Integer goodsId, Integer inventoryQuantity, double purchasingPrice) {
        // TODO 添加库存需要生成进货单、进货单商品列表
        Goods goods = goodsDao.getGoodsById(goodsId);
        if (goods != null) {
            goods.setInventoryQuantity(goods.getInventoryQuantity() + inventoryQuantity);
            goods.setLastPurchasingPrice(goods.getPurchasingPrice());
            goods.setPurchasingPrice(purchasingPrice);
        }
        int count = goodsDao.UpdateGoods(goods);
        if (count > 0) {
            return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS, count);
        }
        return new ServiceVO<>(ErrorCode.UPDATE_OR_ADD_ERROR_CODE, ErrorCode.UPDATE_OR_ADD_ERROR_MESS, count);
    }

    @Override
    public ServiceVO<Object> deleteStock(Integer goodsId) {
        //判断商品的状态
        Goods goods = goodsDao.getGoodsById(goodsId);
        //判断商品的状、入库、有进货销售单据不能删除
        if (goods.getState() == 0) {
            int count = goodsDao.deleteGoodsByGoodsId(goodsId);
            if (count > 0) {
                return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS, count);
            }
        } else if (goods.getState() == 1) {
            return new ServiceVO<>(ErrorCode.STORED_ERROR_CODE, ErrorCode.STORED_ERROR_MESS, goods.getGoodsId());
        } else if (goods.getState() == 2) {
            return new ServiceVO<>(ErrorCode.HAS_FORM_ERROR_CODE, ErrorCode.HAS_FORM_ERROR_MESS, goods.getGoodsId());
        }
        return new ServiceVO<>(ErrorCode.DELETE_ERROR_CODE, ErrorCode.DELETE_ERROR_MESS, goods.getGoodsId());
    }

    /**
     * 库存报警
     *
     * @return Map
     */
    @Override
    public Map<String, Object> listAlarm() {
        Map<String, Object> result = new HashMap<>();
        List<Goods> resultGoodsList = new ArrayList<>();
        //查询当前库存小于库存下限的商品
        List<Goods> goods = goodsDao.listInventory(null, null, null, null);
        if (goods != null) {
            goods.forEach(good -> {
                if (good.getInventoryQuantity() < good.getMinNum()) {
                    resultGoodsList.add(good);
                }
            });
            int total = resultGoodsList.size();
            result.put("total", total);
            result.put("rows", resultGoodsList);
            return result;
        }
        return result;
    }

    /**
     * 查询所有商品信息
     *
     * @param page        页码
     * @param rows        行数
     * @param codeOrName  商品名称或code
     * @param goodsTypeId 商品类型Id
     * @return Map
     */
    private Map<String, Object> getResultMap(Integer page, Integer rows, String codeOrName, Integer goodsTypeId) {
        Map<String, Object> result = new HashMap<>();

        List<Goods> resultGoodsList = new ArrayList<>();
        // 计算页码
        page = (page - 1) * rows;
        Integer finalPage = page;
        // 判断goodsTypeId是否为空
        if (goodsTypeId == null) {
            //调用首页那个接口查询所有商品
            List<Goods> goods = goodsDao.listInventory(finalPage, rows, codeOrName, goodsTypeId);
            goods.forEach(good -> {
                if (good.getSaleTotal() == null) {
                    good.setSaleTotal(0);
                }
                resultGoodsList.add(good);
            });
        } else {
            //通过goodsTypeId
            //递归查询当前类型下的所有子类型
            List<GoodsType> goodsTypeByParentId = goodsTypeDao.getGoodsTypeByParentId(goodsTypeId);
            List<Integer> goodsTypeIds = collectGoodsTypeIdsRecursive(goodsTypeByParentId);
            if (goodsTypeIds.isEmpty()) {
                // 获取商品信息
                List<Goods> goodsList = goodsDao.listInventory(finalPage, rows, codeOrName, goodsTypeId);
                resultGoodsList.addAll(goodsList);
            }
            goodsTypeIds.forEach(goodsTypeId1 -> {
                // 获取商品信息
                List<Goods> goodsList = goodsDao.listInventory(finalPage, rows, codeOrName, goodsTypeId1);
                resultGoodsList.addAll(goodsList);
            });
        }

        int total = resultGoodsList.size();

        result.put("total", total);
        result.put("rows", resultGoodsList);
        return result;
    }

    /**
     * 递归查询当前类型下的所有子类型Id
     *
     * @param goodsTypeList 所有类型集合
     * @return Ids
     */
    private List<Integer> collectGoodsTypeIdsRecursive(List<GoodsType> goodsTypeList) {
        List<Integer> goodsTypeIds = new ArrayList<>();
        for (GoodsType goods : goodsTypeList) {
            if (goods == null) {
                return goodsTypeIds;
            }
            Integer currentTypeId = goods.getGoodsTypeId();
            if (currentTypeId != null) {
                // 添加当前层级的商品类型ID
                goodsTypeIds.add(currentTypeId);
                // 获取下一层级的商品类型
                List<GoodsType> childTypes = goodsTypeDao.getGoodsTypeByParentId(currentTypeId);
                // 递归处理子层级
                collectGoodsTypeIdsRecursive(childTypes);
            }
        }
        return goodsTypeIds;
    }


}
